import { getAction } from '@/api/manage'
import { Message } from 'element-ui'

class WebSocketService {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.heartbeatInterval = null
    this.subscribers = new Map()
  }

  // 获取WebSocket服务器地址
  async getWebSocketUrl() {
    try {
      // 使用与API相同的方式获取服务器地址
      const response = await getAction('/sys/getWebSocketUrl')
      if (response.success) {
        // 将http(s)转换为ws(s)
        const wsUrl = response.result.replace(/^http/, 'ws')
        return `${wsUrl}/statistics/websocket`
      }
      throw new Error('获取WebSocket地址失败')
    } catch (error) {
      console.error('获取WebSocket地址失败:', error)
      throw error
    }
  }

  // 连接WebSocket
  async connect() {
    try {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        return
      }

      const wsUrl = await this.getWebSocketUrl()
      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        console.log('WebSocket连接成功')
        this.reconnectAttempts = 0
        this.startHeartbeat()
      }

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          this.handleMessage(data)
        } catch (error) {
          console.error('处理WebSocket消息失败:', error)
        }
      }

      this.ws.onclose = () => {
        console.log('WebSocket连接关闭')
        this.stopHeartbeat()
        this.reconnect()
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        this.stopHeartbeat()
      }
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.reconnect()
    }
  }

  // 重新连接
  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      Message.error('WebSocket连接失败，请刷新页面重试')
      return
    }

    this.reconnectAttempts++
    console.log(`尝试第${this.reconnectAttempts}次重新连接...`)
    
    setTimeout(() => {
      this.connect()
    }, this.reconnectInterval)
  }

  // 开始心跳
  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({ type: 'heartbeat' }))
      }
    }, 30000) // 每30秒发送一次心跳
  }

  // 停止心跳
  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
  }

  // 订阅数据更新
  subscribe(type, callback) {
    if (!this.subscribers.has(type)) {
      this.subscribers.set(type, new Set())
    }
    this.subscribers.get(type).add(callback)

    // 如果WebSocket未连接，则连接
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      this.connect()
    }
  }

  // 取消订阅
  unsubscribe(type, callback) {
    if (this.subscribers.has(type)) {
      this.subscribers.get(type).delete(callback)
    }
  }

  // 处理接收到的消息
  handleMessage(data) {
    const { type, payload } = data
    
    if (type === 'heartbeat') {
      return
    }

    if (this.subscribers.has(type)) {
      this.subscribers.get(type).forEach(callback => {
        try {
          callback(payload)
        } catch (error) {
          console.error('处理订阅消息失败:', error)
        }
      })
    }
  }

  // 关闭连接
  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    this.stopHeartbeat()
    this.subscribers.clear()
  }
}

export const websocketService = new WebSocketService() 